package cn.swu.cs.lessonten

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContentResolverCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.security.Permission
import java.util.ArrayList

class MainActivity : AppCompatActivity() {

    val TAG = "@@Main"

    val REQ_CODE = 1024
    val REQ_CODE_CONTACT = 1025

    lateinit var mAdapter: ContactAdapter

    var toCallPhone:String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mAdapter = ContactAdapter()

        findViewById<RecyclerView>(R.id.recycler).apply {
            this.layoutManager = LinearLayoutManager(this@MainActivity)
            this.adapter = mAdapter
        }

        toReadContacts()

        toReadFromTodo()

//        findViewById<Button>(R.id.btn).setOnClickListener {
//            toCall()
//        }
    }

    private fun toReadFromTodo() {
        val authority = "cn.swu.cs.lessonnine.provider"
        val uri = Uri.parse("content://$authority/todo")
        val cursor = ContentResolverCompat.query(contentResolver,uri,null,null,null,null,null)

        while (cursor.moveToNext()){
            val idx = cursor.getColumnIndex("id")
            val id = cursor.getString( Math.max(idx,0))
            val idxContent = cursor.getColumnIndex("content")
            val content = cursor.getString(Math.max(idxContent,0))

            Log.d(TAG,"read from todo provider: id= $id, content = $content")
        }
    }

    private fun toReadContacts() {
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS)
            == PackageManager.PERMISSION_GRANTED){
            readContacts()
        }else{
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS),REQ_CODE_CONTACT)
        }
    }

    private fun readContacts() {

        val cursor = ContentResolverCompat.query(contentResolver,
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,
            null,
            null,
            null,
            null
        )
        val arr = arrayListOf<Contact>()
        while (cursor.moveToNext()){
            val nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
            val phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
            if(nameIdx >= 0) {
                val name = cursor.getString(nameIdx)
                val phone = cursor.getString(phoneIdx)
                arr.add(Contact(name,phone))
            }
        }

        mAdapter.setData(arr)


    }

    private fun toCall(phone:String) {
        if(ContextCompat.checkSelfPermission(this,Manifest.permission.CALL_PHONE)
         == PackageManager.PERMISSION_GRANTED){
            doCall(phone)
        }else{
//            requestPermissions()
            toCallPhone = phone
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),REQ_CODE)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == REQ_CODE){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                toCallPhone?.let{
                    doCall(it)
                }
            }else{
                Toast.makeText(this,"您必须授权才能拨打电话",Toast.LENGTH_LONG).show()
            }
        }else if(requestCode == REQ_CODE_CONTACT){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                readContacts()
            }else{
                Toast.makeText(this,"您必须授权才能读取联系人",Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun doCall(phone: String) {
        val intent = Intent(Intent.ACTION_CALL)
        intent.data = Uri.parse("tel:$phone")

        startActivity(intent)
    }


    data class Contact(var name:String,var phone:String)

    inner class ContactAdapter : RecyclerView.Adapter<ContactViewHolder>() {

        private var data = arrayListOf<Contact>()

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_contact,parent,false)
            return ContactViewHolder(view).apply {
                this.txtName = view.findViewById(R.id.name)
                this.txtPhone = view.findViewById(R.id.phone)
                this.btnCall = view.findViewById(R.id.btn_call)
            }
        }

        override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
            holder.render(data[position])
        }

        override fun getItemCount(): Int {
            return data.size
        }

        fun setData(arr: ArrayList<Contact>) {
            data = arr
            notifyDataSetChanged()
        }
    }

    inner class ContactViewHolder(view: View) : RecyclerView.ViewHolder(view){

        var txtName:TextView? = null
        var txtPhone:TextView? = null

        var btnCall:TextView? = null

        fun render(contact: Contact) {

            txtName?.text = contact.name
            txtPhone?.text = contact.phone
            btnCall?.setOnClickListener {
                toCall(contact.phone)
            }

        }

    }
}